package com.kgc.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * Created on 2021/6/21.
 * Author: lzy
 * Description: 自定义线程池配置类
 */
@Configuration
@EnableAsync
@Slf4j
public class TaskExcutorConfig {
    // 从配置文件中读取自定义配置
    // 核心线程数
    @Value("${async.thread.core_pool_size}")
    private Integer corePoolSize;

    // 最大线程数
    @Value("${async.thread.max_pool_size}")
    private Integer maxPoolSize;

    // 缓存队列的容量
    @Value("${async.thread.quene.capacity}")
    private Integer queueCapacity;

    @Bean
    public Executor asyncServiceExecutor(){
        log.info("----- asyncServiceExecutor begin ------");

        // 设置任务调度器
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 设置核心线程数，允许系统一直保留此处指定的线程数大小，存放在线程池中
        executor.setCorePoolSize(corePoolSize);

        // 设置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 设置队列缓存大小
        executor.setQueueCapacity(queueCapacity);

        // 自定义线程别名
        executor.setThreadNamePrefix("kgc-async-thread-");

        // 注意：必须调用初始化方法，让自定义配置生效
        executor.initialize();

        log.info("----- asyncServiceExecutor end ------");
        return executor;
    }


}
